<template>
   <div class="app-container">
    <el-card class="operate-container" shadow="never">
      
       <el-form :inline="true" label-position="right" size="mini">
       <el-form-item label="学科："   size="mini">
       <el-select  v-model="subjectId" placeholder="请选择学科"   size="mini">
                  <el-option
                    v-for="item in subjectOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
         </el-select>
     </el-form-item>
      <el-form-item label="阶段"  size="mini">
      
          <el-cascader v-model="level"
                    :options="levelOptions"
                    size="mini"
                    :props="levelprops"
                    collapse-tags
                    ></el-cascader>
     </el-form-item>
         <el-button
       
        @click="searchKnowledge()"
        size="mini">
        查询
      </el-button>
     </el-form>
      
    </el-card>
    <el-card>
    	<el-tree
		  :props="props"
		  :data="treedata"
		  ref="mytree"
		  :expand-on-click-node="false"
		  :default-expanded-keys="expandedkeys"
		  node-key="id"
		 
		  @node-click="handleNodeClick">
		  <span class="custom-tree-node" slot-scope="{ node, data }">
	        <span style="font-size:12px">{{ node.label }}</span>
	        <span >
	          <el-button 
	            type="text"
	            size="mini"
	            @click="showAddDialog(node, data)">
	            添加子节点
	          </el-button>
	          <el-button  v-if="node.level>1"
	            type="text"
	            size="mini"
	            @click="showUpdateDialog(node, data)">
	            编辑
	          </el-button>
	          <el-button v-if="node.level>1"
	            type="text"
	            size="mini"
	            @click="handleDelete(node,data)">
	            删除
	          </el-button>
	        </span>
	      </span>
      	</span>

		</el-tree>


    </el-card>
    <el-card>
  			<span font-size="12px">{{content}}</span>
  	</el-card>

<el-dialog title="添加知识点" :close-on-click-modal='false' :visible.sync="addFormVisible">

	  <el-form :model="addForm" ref="addFormRef" :rules="addFormRule">
	   
	  	<span font-size="12px">学科:{{subjectId | optionFilter(subjectOptions)}}</span> 	
	  	<el-form-item label="阶段名称"  prop="level">
	    	 <el-cascader v-model="addForm.level"
                    :options="levelOptions"
                    size="mini"
                    :props="levelprops"
                    collapse-tags
                    ></el-cascader>
	    </el-form-item>

	    <el-form-item label="知识点名称"  prop="name">
	      <el-input v-model="addForm.name" size="mini" autocomplete="off"></el-input>
	    </el-form-item>
	    <el-form-item label=" 知识点说明：">
        
         	<el-input
			  type="textarea"
			  autosize
			  placeholder="请输入内容"
			  v-model="addForm.comment">
			</el-input>
         
      </el-form-item>
	    
	     
	    
	  </el-form>
	  <div slot="footer" class="dialog-footer">
	    <el-button @click="addFormVisible = false">取 消</el-button>
	    <el-button type="primary" @click="handleAdd()">确 定</el-button>
	  </div>
 </el-dialog>

   <el-dialog  width="80%" top="1vh"  title="修改知识点"  :close-on-click-modal='false' :visible.sync="updateFormVisible">
   		<span font-size="12px">学科:{{subjectId | optionFilter(subjectOptions)}}</span> 	
	  <el-form :model="updateForm"  ref="updateFormRef" :rules="updateFormRule">
	  
	  	<el-form-item label="阶段名称"  prop="level">
	    	 <el-cascader v-model="updateForm.level"
                    :options="levelOptions"
                    size="mini"
                    :props="levelprops"
                    collapse-tags
                    ></el-cascader>
	    </el-form-item>

	    <el-form-item label="知识点名称"  prop="name">
	      <el-input v-model="updateForm.name" size="mini" autocomplete="off"></el-input>
	    </el-form-item>

	    <el-form-item label=" 知识点说明：">
	    	<el-input
			  type="textarea"
			  autosize
			  placeholder="请输入内容"
			  v-model="updateForm.comment">
			</el-input>

        
         	
         
      </el-form-item>
	    
	     
	    
	  </el-form>
	  <div slot="footer" class="dialog-footer">
	    <el-button @click="updateFormVisible = false">取 消</el-button>
	    <el-button type="primary" @click="handleUpdate()">确 定</el-button>
	  </div>
  </el-dialog>

  
  </div> 

 

    
</template>
<script type="text/javascript">
	
	
	import {mapGetters} from 'vuex'
	import store from '@/store'
	import {fetchList as fetchKnowledgeList} from '@/api/knowledge'
	import {add as addKnowledge, deletes as deleteKnowledge} from '@/api/knowledge'
	import {get as getKnowledge, update as updateKnowledge} from '@/api/knowledge'

	
	export default {
	    name: "knowledgeTree",

	    data() {
	      return {
	      	 //默认展开的节点key
	      	 expandedkeys:[],
	      	 subjectId:null,
	      	 knowledgeContent:'',
	      	 level:null,
	      	 content:null,
	      	 contentVisible:false,
	      	 //添加知识点对话框相应的数据
	         addFormVisible:false,
	         addForm:{
	        	name:null,
	        	level:[],
	        	comment:null
	         },
	         addFormRule :{
	          name: [{required: true, message: '请输入知识点名称', trigger: 'blur'}],
	          level: [{required: true, message: '请选择阶段', trigger: 'blur'}],
	          
	        },

	        updateFormVisible:false,
	        updateForm:{
	        	name:null,
	        	level:[],
	        	comment:null,
	        	
	         },
	         updateFormRule :{
	          name: [{required: true, message: '请输入知识点名称', trigger: 'blur'}],
	          level: [{required: true, message: '请选择阶段', trigger: 'blur'}],
	          
	        },

	      	 //阶段状态的选项
        	 levelprops: { multiple: true },
	      	 props: {
		          label: 'name',
		          children: 'children',
		          
		        },

		    treedata:null,       

		    
	      }
	    },
	    computed:{
	    	...mapGetters([
	          'subjectOptions',
	          'levelOptions',
	          
	          'allLevelList'
	        ]),

	    	/*
	    	level id 字典
	    	 key=level id
	    	 value=父level  id
	    	*/
	    	levelDic : function(){
	    		var dic=new Array()
	    		let allLevelList=this.allLevelList
	    		for (var i=0;i<allLevelList.length;i++){
	    			dic[allLevelList[i].id]=allLevelList[i].parentId

	    		}
	    		return dic

	    	},
	    	
	    	




	    },
	    filters: {
	      optionFilter(value,options) {
	        let res= options.find(function(x) {
	          return x.value ===value;
	          }
	        )
	        if (res){
	          return res.label
	        }else{
	          return ''
	        }
	      },
    	},
	    created:function(){ 
	    
	    	this.subjectId=this.subjectOptions[0].value

	    },
	    methods:{
	    	
	    	handleNodeClick(data){
	    	
	    		if (data.id!=0){
	    			getKnowledge({"id":data.id}).then(response=>{
      					this.content=response.data.content
		    		
					}).catch(error => {
			       	});

	    			this.contentVisible=true
	    			
	    		}else{
	    			this.contentVisible=false
	    		}
	    		

	    	},
	    	/*
	    	输入是LevelID
	    	输出是它的父亲节点，祖父节点...直到 ParentId=0 [],
	    	用于在阶段选择下拉框中选中相应的阶段
	    	*/
	    	getLevelParentPath(levelId){
	    		
	    		var parentsPath=[levelId]
	    		var parentId=this.levelDic[levelId]
	    		while (parentId!=0){
	    			parentsPath.unshift(parentId)
	    			parentId=this.levelDic[parentId]

	    		}
	    		
	    		return parentsPath

	    	},
	    	showUpdateDialog(node,data){
	    		this.updateForm.name=data.name
	    		this.updateFormVisible=true
	    		
	    		this.updateForm.data=data
	    		this.updateForm.level=[]
	    		
	    		let updatelevels= data.levelIds.split(',')
	    		
	    		
	    		for (var i=0;i<updatelevels.length;i++){
	    			this.updateForm.level.push(this.getLevelParentPath(updatelevels[i]))
	    		}

	    		getKnowledge({"id":data.id}).then(response=>{

				        		
	    			this.updateForm.comment=response.data.comment

					    		
				}).catch(error => {

		          				
		          
		       	});

	    		


	    		
	    	},

	    	showAddDialog(node,data){
	    		this.addForm.name=''
	    		this.addFormVisible=true
	    		
	    		this.addForm.data=data
	    		this.addForm.level=[]
	    		this.addForm.comment=""
	    	},
	    	handleDelete( node,data) {
		        this.$confirm('是否要删除该知识点？如果删除，将彻底删除所有子知识点，以及相关的试题！', '提示', {
		          confirmButtonText: '确定',
		          cancelButtonText: '取消',
		          type: 'warning'
		        }).then(() => {
		          	 this.$confirm('再次确认删除该该知识点及子知识点？', '提示', {
				          confirmButtonText: '确定',
				          cancelButtonText: '取消',
				          type: 'warning'
				        }).then(() => {
				        	deleteKnowledge({"id":data.id}).then(response=>{

				        		const parent = node.parent;
						        const children = parent.data.children || parent.data;
						        const index = children.findIndex(d => d.id === data.id);
						        children.splice(index, 1);


					    		
					    	}).catch(error => {

		          				this.$message({
					                type: 'error',
					                message: '删除失败',
					                duration:1000
					            });
		          
		       				});


				        }).catch(() => {
		          				
		          
		       			 });
		          
		        }).catch(() => {
		          	
		          
		        });
		      },
	    	handleAdd(){
	    		
	    		this.$refs.addFormRef.validate(valid => {
	    			if (valid) {

			    		let levelParams=[]
			    		let addLevel=this.addForm.level
			    		
			    		for (let i = 0; i < addLevel.length; i++) {
				            levelParams.push(addLevel[i][addLevel[i].length-1]);
		          		}
		          		
		          		let parentId= this.addForm.data.id
		          		
			    		addKnowledge({"subjectId":this.subjectId,
			    			"levelIds":levelParams.join(','),
			    			"parentId":parentId,
			    			"name":this.addForm.name,
			    			"comment":this.addForm.comment}).then(response=>{
				        			
						    let newid=response.data.id;
						   
				        
					        //this.$refs.mytree.append(newChild,node)
					        const newChild = { id: newid, name: this.addForm.name};
					        if (!this.addForm.data.children) {
					          this.$set(this.addForm.data, 'children', []);
					        }
					        this.addForm.data.children.push(newChild);

					        this.searchKnowledge()
					        this.addFormVisible = false
					        this.expandedkeys=[newid]


					    			

					    }).catch(error=>{
					    	console.log(error)
					    	this.$message({
						                type: 'error',
						                message: '增加知识点失败',
						                duration:1000
						             });
					    	this.addFormVisible = false

					     })
					}
				})


	    	},
	    	handleUpdate(){
	    		this.$refs.updateFormRef.validate(valid => {
	    			if (valid) {
	    				
		          		let data
		          		data = this.updateForm.data
		          		let id= data.id
		          		
		          		let levelParams=[]
				    	let addLevel=this.updateForm.level
				    		
				    	for (let i = 0; i < addLevel.length; i++) {
					            levelParams.push(addLevel[i][addLevel[i].length-1]);
			          	}

		          		var updateParams = {
							id: id,
							
						} 
						updateParams.name=this.updateForm.name
						let level=levelParams.join(',')
						updateParams.comment=this.updateForm.comment
						
						

						if (level != data.level){
							updateParams.levelIds=level
					
						}
						

							//除了传入ID以外，至少有一项内容要更新
						updateKnowledge(updateParams).then(response=>{
				        		this.$message({
						                type: 'success',
						                message: '更新知识点成功',
						                duration:1000
						             });
				        		this.searchKnowledge()
				        		 this.expandedkeys=[id]

					   	}).catch(error=>{
					    	console.log(error)
					    	this.$message({
						                type: 'error',
						                message: '更新知识点失败',
						                duration:1000
						             });
					    	

					    })

						
						this.updateFormVisible = false
			    		

	    			}
	    		})


	    	},
	      searchKnowledge(){
	      		if (this.level===null){
	    	  		this.$message({
				                type: 'warning',
				                message: '请选择阶段',
				                duration:1000
				             });
	    	  		return
	    	  	}

	      		/*这里传进来的level是一个二位数组,比如
	      		[
		      		[1,2]
		      		[1,3]
		      		[1,4]
	      		]
				表示所有选择的阶段（以及他们的父阶段），传递到server的参数是最后一层的阶段，用逗号隔开
	      		*/
	      		let levelParams=[]

	    		for (let i = 0; i < this.level.length; i++) {
		            levelParams.push(this.level[i][this.level[i].length-1]);
          		}

	      		fetchKnowledgeList({"subjectId":this.subjectId,"levelIds":levelParams.join(',')}).then(response=>{
		        			
				    this.treedata=response.data.list;
			    			

			    }).catch(error=>{

			    	reject(error)

			     })


	     },

	    	
	    
	    }
	    
	}
	
	
</script>